import React,{useState,useEffect} from "react";
import { useNavigate,useParams } from "react-router-dom";
import {$getother } from "../../api/mineapi";
import {
    CloseCircleOutlined,
    DownOutlined,
    ManOutlined,
    PlusOutlined,
    SettingOutlined,
    WomanOutlined
} from '@ant-design/icons';
import {AutoComplete, Button, Drawer, Form, Input} from "antd";
import UploadImg from "../../uploadImg/uploadImg";
import Post from "../../components/post/post";
import { $getImg } from "../../api/getImgapi";
import {$getFollow,$cancelFollow,$handleFollow,$getFollowCount,$getOtherPosts,$getTagList} from "../../api/orthermineapi";
export default function OtherMine(){
    //获取传递从图像传递过来的参数
    const { studentId } = useParams();
  //获取帖子的数据
  const [posts, setPosts] = useState([]);
  const [page, setPage] = useState(1);
  const [loading, setLoading] = useState(false);
     //导航
     const navigate = useNavigate();
      // 使用 state 来控制下拉框的显示状态
        const [isDropdownVisible, setDropdownVisible] = useState(false);
        //控制下拉框的状态
        const  Dropdown=()=>{
                setDropdownVisible(!isDropdownVisible);
        }
        //size
    const [size, setSize] = useState('large');
    //为了讲useEffect中获取的图片数据在return中获得
    const [imgdata, setImgData] = useState(null);
    //获取头像主页的数据
    const [photoinformation,setPhotoinformation]=useState({});
    //显示关注按钮的状态
    const [backendData, setBackendData] = useState(0);
    //获取关注双方的关系
    const [followship,setFollowship]=useState(0);
    //关注者的数量
    const [followcount,setFollowcount]=useState(0);
    //关注的数量
    const [bfollowcount,setBfollowcount]=useState(0);
    //获取标签列表的数据
    const [typelist, setTypeList] = useState([]);
    //提交菜单
    const onFinish = async(values) => {
            // if(roleId){
            //     const {data:{ message, success }}=await $update(values)
            // if(success){
            //     setNotiMsg({type:'success',description:message})
            //     loadList()
            // }else{
            //     setNotiMsg({type:'error',description:message})
            // }

            // }else{
            //     const {message,success}=await $add(values)
            // if(success){
            //     setNotiMsg({type:'success',description:message})
            //     loadList()
            //     clear()
            // }else{
            //   console.log(message)
            //     setNotiMsg({type:'error',description:message})
            // }
            // }


          };


      const fetchData = async () => {
        try {

              //获取他人信息
          const response = await $getother({ studentId:studentId.toString()});
            setPhotoinformation(response.data);
          //获取个人头像
          const response3=$getImg({ studentId: response.data.studentId.toString() });
          response3.then((result) => {
            if(result.code===1){
              const { data } = result;
              setImgData(data);
            }
            });
            //获取用户标签列表
            const response2 = await $getTagList({studentId:response.data.studentId.toString()});
            if(response2.code) {
                setTypeList(response2.data);
            }
        } catch (error) {
          console.error("Error fetching data:", error);
        }
      };
      //获取帖子的信息
      const fetchPosts = async () => {
        try {
          const response = await $getOtherPosts({page:page.toString(),pageSize:'10',studentId:studentId});
          if(response.code===1){
          setPosts(response.data); // 假设响应的数据结构是一个数组
          }
        } catch (error) {
          console.error('Error fetching posts:', error);
        }
      };
      //在页面滑倒最底下时调用函数加载
      const fetchMorePosts = async () => {
        if (loading) return; // 防止重复加载
        try {
          setLoading(true);
          const nextPage = page + 1;
          const response = await $getPosts({page:page.toString(),pageSize:'10',flag:'0'});
          setPosts(prevPosts => [...prevPosts, ...response.data]);
          setPage(nextPage);
        } catch (error) {
          console.error('Error fetching more posts:', error);
        } finally {
          setLoading(false);
        }
      };
      useEffect(() => {
              fetchData();//获取个人信息数据
              fetchPosts();//获取帖子数据
          getFollowship();//获取用户与该图像用户的关系
          getfollowcount();//获取关注者和被关注的人的数量


    }, [studentId]); // 确保依赖项数组为空或包含正确的依赖项
    //在帖子滑到最底端的时候获取新的posts值
    useEffect(() => {
      const handleScroll = () => {
        // 在这里可以获取到最新的 posts 值
        if (
          window.innerHeight + document.documentElement.scrollTop ===
          document.documentElement.offsetHeight
        ) {
          fetchMorePosts();
        }
      };

      window.addEventListener('scroll', handleScroll);

      return () => {
        window.removeEventListener('scroll', handleScroll);
      };
    }, [posts]);
    //点击关注按钮
    const handlefollow= async ()=>{
            switch (backendData) {
                case 0:
                    setBackendData(1); // 从关注切换为已关注
                    await $handleFollow({ studentId: studentId.toString() });
                    break;
                case 1:
                    setBackendData(0); // 从已关注切换为关注
                    await $cancelFollow({ studentId: studentId.toString() });
                    break;
                case 2:
                    setBackendData(0); // 从互关切换为关注
                    await $cancelFollow({ studentId: studentId.toString() });
                    break;
                default:
                    setBackendData(0);
                    break;
            }
        };

    //获取双方关注的关系
    const getFollowship=async()=>{
        const response= await $getFollow({ studentId:studentId.toString()});
      setBackendData(response.data);
    }
    //获取关注者和被关注者的数量
    const getfollowcount=async ()=>{

        const response = await  $getFollowCount({ studentId:studentId.toString()});
        setFollowcount(response.data.follow);
        setBfollowcount(response.data.fan);
    }
    // 根据后端数据渲染按钮文本
    let buttonText;
    switch (backendData) {
        case 0:
            buttonText = '关注';
            break;
        case 1:
            buttonText = '已关注';
            break;
        case 2:
            buttonText = '互关';
            break;
        default:
            buttonText = '关注';
            break;
    }
    // 根据后端数据渲染按钮样式类名
    let buttonClassName;
    switch (backendData) {
        case 0:
            buttonClassName = 'default';
            break;
        case 1:
            buttonClassName = 'primary';
            break;
        case 2:
            buttonClassName = 'primary';
            break;
    }
    let buttonstyle;
    switch (backendData) {
        case 0:
            buttonstyle = {backgroundColor:'white'};
            break;
        case 1:
            buttonstyle = {backgroundColor:'rgb(137, 222, 215)',color:'white'};
            break;
        case 2:
            buttonstyle = {backgroundColor:'rgb(137, 222, 215)',color:'white'};
            break;
    }
    return (
        <div style={{width: '80vw', marginLeft: '150px', marginTop: '10px'}}>
            <div className='Top' style={{height: '45vh'}}>
                <div className='Topgreen' style={{height: '27vh', backgroundColor: 'rgb(137, 222, 215)'}}></div>
                <div className='Topwhite' style={{height: '18vh', backgroundColor: 'white'}}>
                    <div className='TopWhiteCenter' style={{marginLeft: '250px'}}>
                        <div className="NickName"
                             style={{fontWeight: 'bold', fontSize: '20px'}}>{photoinformation.nickname}</div>
                        <div className='Center'
                             style={{marginTop: '5px', display: 'flex', justifyContent: 'space-between'}}>
                            <div className='sex&&information'>
                                <Button icon={photoinformation.sex === 'F' ? <WomanOutlined/> : <ManOutlined/>}
                                        style={photoinformation.sex === 'F' ? {
                                            border: 'none',
                                            color: 'rgb(255, 192, 203)'
                                        } : {border: 'none', color: 'rgb(0, 0, 255)'}}></Button>
                                <span>{photoinformation.briefIntroduction}</span>
                            </div>
                            <div className='follow' style={{marginRight: "150px", display: 'flex'}}>
                                <div className='f' style={{borderRight: '2px solid rgb(0,0,0)'}}>
                                    <div>
                                        <div style={{marginRight: '20px', color: 'rgb(134,133,133)'}}>关注</div>
                                        <div style={{
                                            fontWeight: 'bold',
                                            marginLeft: '6px',
                                            fontSize: '20px'
                                        }}>{bfollowcount}</div>
                                    </div>

                                </div>
                                <div className='bf' style={{marginLeft: '20px'}}>
                                    <div style={{color: 'rgb(134,133,133)'}}>关注者</div>
                                    <div style={{
                                        fontWeight: 'bold',
                                        marginLeft: '12px',
                                        fontSize: '20px'
                                    }}>{followcount}</div>
                                </div>
                            </div>
                        </div>
                        <div style={{display: 'flex', marginTop: '10px'}}>
                            {typelist.map((tag, index) => (
                                <span key={index} style={{
                                    marginLeft: '30px',
                                    backgroundColor: 'rgb(88, 209, 200)',
                                    color: 'white',
                                    borderRadius: '15px',
                                    padding: '5px'
                                }}>
                                <span>{tag.tagName}</span>
                            </span>
                            ))}
                        </div>
                        <div style={{position: 'absolute', top: '50vh', left: '74vw', zIndex: 999}}>
                            <Button onClick={handlefollow} style={buttonstyle}>{buttonText}</Button>
                        </div>
                    </div>
                </div>
                <div className='picture' style={{position: 'relative', top: '-21vh', left: '5vw'}}>
                    <img src={`data:image/jpeg;base64,${imgdata}`} width='130px' height='130px' alt="获取图片失败"/>
                </div>

            </div>
            <div className='Bottom' style={{marginTop: '10px', minHeight: '100vh', display: 'flex'}}>
                <div className='Bottom-left' style={{width: '60vw', backgroundColor: 'white', minHeight: '100vh'}}>
                    {posts.map((post, index) => (
                        <Post key={index} post={post}  avater={imgdata}/>
                    ))}
                </div>
                <div className='Bottom-right'
                     style={{width: '20vw', backgroundColor: 'white', height: '350px', marginLeft: '10px'}}>
                    <div className='selfinformation'>
                        <div className='top'
                             style={{display: 'flex', justifyContent: 'space-between', marginTop: '20px'}}>
                            <div style={{
                                color: 'rgb(138, 223, 216)',
                                fontWeight: 'bold',
                                fontSize: '15px',
                                marginLeft: '20px'
                            }}>个人资料
                            </div>
                        </div>
                        <div className='Bottom'>
                            <div style={{marginLeft: '20px', marginTop: '20px'}}>
                                <span>昵称：</span>
                                <span>{photoinformation.nickname}</span>
                            </div>
                            <div style={{marginLeft: '20px', marginTop: '20px'}}>
                                <span>性别：</span>
                                <span>{photoinformation.sex === 'F' ? '女' : '男'}</span>
                            </div>
                            <div style={{marginLeft: '20px', marginTop: '20px'}}>
                                <span>生日：</span>
                                <span>{photoinformation.birthday}</span>
                            </div>
                            <div style={{marginLeft: '20px', marginTop: '20px'}}>
                                <span>邮件：</span>
                                <span>{photoinformation.email}</span>
                            </div>
                            <div style={{marginLeft: '20px', marginTop: '20px'}}>
                                <span>公司：</span>
                                <span>{photoinformation.currentCompany}</span>
                            </div>
                            <div style={{marginLeft: '20px', marginTop: '20px'}}>
                                <span>职位：</span>
                                <span>{photoinformation.position}</span>
                            </div>
                            <div style={{marginLeft: '20px', marginTop: '20px'}}>
                                <span>个人简介：</span>
                                <span>{photoinformation.brief_introduction}</span>
                            </div>
                        </div>
                    </div>
                </div>
            </div>
        </div>
    )
}